package service

import (
	"fmt"
	cloudauth "github.com/alibabacloud-go/cloudauth-20190307/v3/client"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/aliyun/credentials-go/credentials"
	sferrors "lib/sf-errors"
	"time"
)

func CreateClient(endpoint *string) (_result *cloudauth.Client, _err error) {
	//阿里云账号AccessKey拥有所有API的访问权限，建议您使用RAM用户进行API访问或日常运维。
	//强烈建议不要把AccessKey ID和AccessKey Secret保存到工程代码里，否则可能导致AccessKey泄露，威胁您账号下所有资源的安全。
	//本示例通过阿里云Credentials工具从环境变量中读取AccessKey，来实现API访问的身份验证。
	// 初始化Credential。
	credential, _err := credentials.NewCredential(nil)
	if _err != nil {
		panic(_err)
	}
	// 初始化Client。
	config := &openapi.Config{
		// 使用Credential配置凭证。
		Credential:      credential,
		Endpoint:        endpoint,
		AccessKeyId:     tea.String("LTAI5t9K6hgZBdgfNjr19oiG"),
		AccessKeySecret: tea.String("VLKzeRtzIIo3N7zJKGo0WchwMXdjAe"),
		// 设置HTTP代理。
		// HttpProxy: tea.String("http://xx.xx.xx.xx:xxxx"),
		// 设置HTTPS代理。
		// HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"),
	}
	//_result = &cloudauth.Client{}
	_result, _err = cloudauth.NewClient(config)
	return _result, _err
}

func CreateIdAliyunCardRequest(userId int64, name, card, metaInfo *string) (string, error) {
	s := "IDENTITY_CARD"
	l := "MOVE_ACTION"
	t := time.Now().Format("20060102150405")
	userIdStr := fmt.Sprintf("%d", userId)
	request := &cloudauth.InitFaceVerifyRequest{
		// 固定值。
		ProductCode: tea.String("ID_PRO"),
		// 请输入场景ID。
		SceneId:      tea.Int64(1000015537),
		OuterOrderNo: tea.String(userIdStr + t),
		Model:        &l,
		// 固定值IDENTITY_CARD。
		CertType: &s,
		CertName: name,
		CertNo:   card,
		MetaInfo: metaInfo,
		// Ip: tea.String("用户IP地址"),
		// UserId: tea.String("用户ID"),
		// Mobile: tea.String("130xxxxxxxx"),
		// CallbackUrl: tea.String("https://www.aliyundoc.com"),
		// CallbackToken: tea.String("xxxxxxx"),
		// 如需开启个人信息加密传输。
		// EncryptType: tea.String("SM2"),
		// CertName: tea.String("BCRD/7ZkNy7Q*****M1BMBezZe8GaYHrLwyJv558w=="),
		// CertNo: tea.String("BMjsstxK3S4b1YH*****Pet8ECObfxmLN92SLsNg==")
	}
	response, _err := InitFaceVerifyAutoRoute(request)
	// 不支持服务自动路由。
	// response, _err := InitFaceVerify(tea.String("cloudauth.cn-shanghai.aliyuncs.com"), request)
	if _err != nil {
		return "", _err
	}
	if *response.Body.Code != "200" {
		return "", sferrors.NewStringf(*response.Body.Message)
	}
	return *response.Body.ResultObject.CertifyId, nil
}

func InitFaceVerifyAutoRoute(request *cloudauth.InitFaceVerifyRequest) (_result *cloudauth.InitFaceVerifyResponse, _err error) {
	endpoints := []*string{tea.String("cloudauth.cn-shanghai.aliyuncs.com"), tea.String("cloudauth.cn-beijing.aliyuncs.com")}
	var lastResponse *cloudauth.InitFaceVerifyResponse
	for _, endpoint := range endpoints {
		response, _err := InitFaceVerify(endpoint, request)
		lastResponse = response
		if _err != nil {
			var err = &tea.SDKError{}
			if _t, ok := _err.(*tea.SDKError); ok {
				err = _t
				// 系统异常，切换到下个地域调用。
				if *err.StatusCode == 500 {
					continue
				}
			}
			return _result, _err
		}

		if *response.StatusCode == 500 {
			continue
		}

		if *response.Body.Code == "500" {
			continue
		}

		_result = response
		return _result, _err
	}
	_result = lastResponse
	return _result, _err
}

func InitFaceVerify(endpoint *string, request *cloudauth.InitFaceVerifyRequest) (_result *cloudauth.InitFaceVerifyResponse, _err error) {
	client, _err := CreateClient(endpoint)
	if _err != nil {
		return _result, _err
	}

	// 创建RuntimeObject实例并设置运行参数。
	runtime := &util.RuntimeOptions{}
	runtime.ReadTimeout = tea.Int(10000)
	runtime.ConnectTimeout = tea.Int(10000)

	_result = &cloudauth.InitFaceVerifyResponse{}
	_body, _err := client.InitFaceVerifyWithOptions(request, runtime)
	if _err != nil {
		return _result, _err
	}
	_result = _body
	return _result, _err
}

func AliyunDecodeOcr(certifyId string) error {
	//对应的id应该是哪个呢 谁获取就是谁的
	var s int64 = 1000015537
	//去设置哪个人呢？
	request := cloudauth.DescribeFaceVerifyRequest{
		// 请输入场景ID。
		SceneId:   &s,
		CertifyId: &certifyId,
	}
	response, _err := DescribeFaceVerifyAutoRoute(&request)

	// 不支持服务自动路由。
	// response, _err := DescribeFaceVerify(tea.String("cloudauth.cn-shanghai.aliyuncs.com"), request)

	if _err != nil {
		return _err
	}
	if *response.Body.Code != "200" {
		return sferrors.NewStringf(*response.Body.Message)
	}
	respBody := *response.Body
	if *respBody.ResultObject.Passed == "F" {
		return sferrors.NewStringf("验证未通过")
	}
	fmt.Println(respBody.ResultObject.UserInfo)

	return _err
}

func DescribeFaceVerifyAutoRoute(request *cloudauth.DescribeFaceVerifyRequest) (_result *cloudauth.DescribeFaceVerifyResponse, _err error) {
	endpoints := []*string{tea.String("cloudauth.cn-shanghai.aliyuncs.com"), tea.String("cloudauth.cn-beijing.aliyuncs.com")}
	var lastResponse *cloudauth.DescribeFaceVerifyResponse
	for _, endpoint := range endpoints {
		response, _err := DescribeFaceVerify(endpoint, request)
		lastResponse = response
		if _err != nil {
			var err = &tea.SDKError{}
			if _t, ok := _err.(*tea.SDKError); ok {
				err = _t
				// 系统异常，切换到下个地域调用。
				if *err.StatusCode == 500 {
					continue
				}
			}
			return _result, _err
		}

		if *response.StatusCode == 500 {
			continue
		}

		if *response.Body.Code == "500" {
			continue
		}

		_result = response
		return _result, _err

	}
	_result = lastResponse
	return _result, _err
}

func DescribeFaceVerify(endpoint *string, request *cloudauth.DescribeFaceVerifyRequest) (_result *cloudauth.DescribeFaceVerifyResponse, _err error) {
	client, _err := CreateClient(endpoint)
	if _err != nil {
		return _result, _err
	}

	// 创建RuntimeObject实例并设置运行参数。
	runtime := &util.RuntimeOptions{}
	runtime.ReadTimeout = tea.Int(10000)
	runtime.ConnectTimeout = tea.Int(10000)

	_body, _err := client.DescribeFaceVerifyWithOptions(request, runtime)
	if _err != nil {
		return _result, _err
	}
	_result = _body
	return _result, _err
}
